import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
    state: {
        userid: "0",
        user: '',
        status: '',
        code: '',
        token: getToken(),
        name: '',
        avatar: '',
        introduction: '',
        roles: [],
        modules: [],
        userInfoExp: {},
        setting: {
            articlePlatform: []
        }
    },

    mutations: {
        SET_USERID: (state, userid) => {
            state.userid = userid
        },
        SET_CODE: (state, code) => {
            state.code = code
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction
        },
        SET_SETTING: (state, setting) => {
            state.setting = setting
        },
        SET_STATUS: (state, status) => {
            state.status = status
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_MODULES: (state, modules) => {
            state.modules = modules
        },
        SET_USERINFOEXP: (state, userInfoExp) => {
            state.userInfoExp = userInfoExp
        }

    },

    actions: {
        // 用户名登录
        LoginByUsername({ commit }, userInfo) {
            const username = userInfo.username.trim()
            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.password).then(response => {
                    const data = response.data
                    commit('SET_TOKEN', data.token)
                    setToken(response.data.token)

                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(response => {
                    if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
                        reject('error')
                    }
                    const data = response.data
                    data.roles = ['admin', 'editor', 'visitor']
                    if (data.is_admin == 1) {
                        data.roles = ['admin']
                    } else if (data.is_admin == 2) {
                        data.roles = ['editor']
                    } else {
                        data.roles = ['visitor']
                    }
                    if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        commit('SET_ROLES', data.roles)
                    } else {
                        reject('没有获取到角色，可以默认角色为admin！')
                    }

                    data.name = data.account
                    data.avatar = "https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191"
                    data.introduction = data.roles[0]


                    // 模块权限
                    data.modules = data.modules || []
                    if (data.modules && data.modules.length > 0) { // 验证返回的roles是否是一个非空数组
                        commit('SET_MODULES', data.modules)
                    }

                    // 具体用户信息
                    data.user_info_exp = data.user_info_exp || null
                    if (data.is_admin == 1) {
                        commit('SET_USERINFOEXP', { bind_account: 'admin' }) //所有权限
                    } else if (!data.user_info_exp) {
                        commit('SET_USERINFOEXP', {
                                bind_account: 'visitor',
                                name: '访问者',
                                jurisdiction: null,
                                equipment: null,
                                group: null,
                                id: 0,
                                pid: 0,
                                create_time: ''
                            }) //访问权限
                    } else {
                        commit('SET_USERINFOEXP', data.user_info_exp)
                    }

                    commit('SET_NAME', data.name)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INTRODUCTION', data.introduction)
                    commit('SET_USERID', data.id)

                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                resolve()
            })
        },

        // 动态修改权限
        ChangeRoles({ commit, dispatch }, role) {
            return new Promise(resolve => {
                commit('SET_TOKEN', role)
                setToken(role)
                getUserInfo(role).then(response => {
                    const data = response.data
                    commit('SET_ROLES', data.roles)
                    commit('SET_NAME', data.name)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INTRODUCTION', data.introduction)
                    dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
                    resolve()
                })
            })
        }
    }
}

export default user